import { createVNode, render } from 'vue';
import ImageConfirm from './ImageConfirm.vue';
export interface ShowImageConfirmOptions {
  title?: string;
  message?: string;
  width?: string;
  confirmButtonText?: string;
  cancelButtonText?: string;
  showClose?: boolean;
  closeOnClickModal?: boolean;
  beforeConfirm?: () => boolean | Promise<boolean>;
  confirmLoading?: boolean;
  disableCancel?: boolean;
}

// 用于挂载的容器
const container = document.createElement('div');
container.className = 'image-confirm-container';
document.body.appendChild(container);

let currentVNode: any = null; // 全局单例 VNode

/**
 * 显示图片确认弹窗
 * @param imageUrl 图片 URL
 * @param options 配置项
 * @returns Promise<void> 确认为 resolve，取消为 reject
 */
export const showImageConfirm = (
  imageUrl: string,
  options: ShowImageConfirmOptions = {}
): Promise<void> => {
  return new Promise<void>((resolve, reject) => {
    // 清除旧实例
    if (currentVNode) {
      render(null, container);
      currentVNode = null;
    }

    // 将 options 作为 props 直接传入 vnode，避免在未挂载时访问 component.exposed
    const vm = createVNode(ImageConfirm, {
      imageUrl,
      // 将配置合并为组件 props
      ...options,
      // 默认打开弹窗（组件内应以 modelValue 控制显示）
      modelValue: true,
      'onUpdate:modelValue': (val: boolean) => {
        if (!val) {
          // 关闭时销毁
          setTimeout(() => {
            render(null, container);
            currentVNode = null;
          }, 300);
        }
      },
      onConfirm: () => {
        resolve();
        // 不立即销毁，让动画完成
        setTimeout(() => {
          render(null, container);
          currentVNode = null;
        }, 300);
      },
      onCancel: () => {
        reject();
        setTimeout(() => {
          render(null, container);
          currentVNode = null;
        }, 300);
      }
    });

    // 渲染
    render(vm, container);
    currentVNode = vm;

    // 如果确实需要在运行时调用组件暴露的方法，可以在渲染后安全地访问 exposed：
    // setTimeout(() => {
    //   vm.component && vm.component.exposed && (vm.component.exposed as any).setOptions?.(options);
    // }, 0);
  });
};
// ...existing code...
